package sys.controller;

import org.springframework.beans.factory.annotation.Autowired;
import sys.core.exception.BusinessException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sys.entity.TbUserEntity;
import sys.entity.User;
import sys.service.TbUserService;
import sys.utils.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

@RestController
@Api(tags = "login接口")
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private TbUserService tbUserService;


    @ApiOperation(value = "登录")
    @PostMapping(value = "/doLogin")
    public User doLogin(@RequestBody User user, HttpServletRequest request) {
        TbUserEntity userEntity = tbUserService.login(user);
        if (userEntity != null) {
            request.setAttribute("name", user.getUserName());
            SessionUtil.onLogin(user, request);
        } else {
            throw new BusinessException("用户名或密码错误");
        }
        return user;
    }

    @ApiOperation(value = "退出登录")
    @PostMapping(value = "/doLogOut")
    public void doLogOut(HttpServletRequest request) {
        SessionUtil.logOut(request);
    }
}
